/**
 * lilang
 * SmFileAction.java
 * 2013-6-24下午6:16:35
 */
package com.cq.oa.web.sm.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oa.base.util.FileUtils;
import oa.base.web.Action.BaseAction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.cq.oa.common.thread.ConvertThread;
import com.cq.oa.common.utils.Convert2swf;
import com.cq.oa.common.utils.ToolUtils;
import com.cq.oa.domain.sm.SmFile;
import com.cq.oa.service.sm.FileService;

/**
 * @author lilang
 *
 */
public class SmFileAction extends BaseAction<SmFile>{

	/**
	 * lilang
	 * 2013-6-24下午7:28:57
	 */
	private static final long serialVersionUID = -7193377022349403988L;


	private static final Log logger = LogFactory.getLog(SmFileAction.class);

	/* (non-Javadoc)
	 * @see oa.base.web.Action.BaseAction#getEntityClass()
	 */
	@Override
	protected Class<SmFile> getEntityClass() {
		// TODO Auto-generated method stub
		return SmFile.class;
	}
	/**
	 * 目标实体名
	 */
	private String targetTableName;
	/**
	 * 目标对象sid
	 */
	private Long targetTableSid;
	/**
	 * 
	 * 附件对象
	 */
	private File[] attachment;
	
	private File[] imgFile;
	/**
	 * 附件名称
	 */
	private String localUrl;
	
	private String[] filename;
	/**
	 * 文件的内容类型
	 */
    private String[] attachmentContentType; 
    /**
     * 上传文件名
     */
    private String[] attachmentFileName;
    /**
     * 附件类型 正式稿/附件稿/正式文稿
     */
    private Integer types;
    /**
     * 临时文件否则 1=是 0=否
     */
    private Integer isTempFile;
    
    private String attachmentType;
    /**
     * 是否只读　0/1
     */
    private Integer isReadOnly;
    /**
     * 是否允许打印 0/1
     */
    private Integer isPrint;
    /**
     * 是否默认显示痕迹 0/1
     */
    private Integer isShowTrack;
    /**
     * 拟稿0/1
     */
    private Integer isCreate;
    /**
     * 红头0/1
     */
    private Integer isRedhead;
    /**
     * 用印0/1
     */
    private Integer isUseSign;
    
    
    
	public File[] getImgFile() {
		return imgFile;
	}
	public void setImgFile(File[] imgFile) {
		this.imgFile = imgFile;
	}
	public String[] getFilename() {
		return filename;
	}
	public void setFilename(String[] filename) {
		this.filename = filename;
	}
	public Integer getIsUseSign() {
		return isUseSign;
	}
	public void setIsUseSign(Integer isUseSign) {
		this.isUseSign = isUseSign;
	}
	public Integer getIsCreate() {
		return isCreate;
	}
	public void setIsCreate(Integer isCreate) {
		this.isCreate = isCreate;
	}
	public Integer getIsRedhead() {
		return isRedhead;
	}
	public void setIsRedhead(Integer isRedhead) {
		this.isRedhead = isRedhead;
	}
	public Integer getIsShowTrack() {
		return isShowTrack;
	}
	public void setIsShowTrack(Integer isShowTrack) {
		this.isShowTrack = isShowTrack;
	}
	public Integer getIsPrint() {
		return isPrint;
	}
	public void setIsPrint(Integer isPrint) {
		this.isPrint = isPrint;
	}
	public String getAttachmentType() {
		return attachmentType;
	}
	public void setAttachmentType(String attachmentType) {
		this.attachmentType = attachmentType;
	}
	public Integer getIsReadOnly() {
		return isReadOnly;
	}
	public void setIsReadOnly(Integer isReadOnly) {
		this.isReadOnly = isReadOnly;
	}
	public String getTargetTableName() {
		return targetTableName;
	}
	public void setTargetTableName(String targetTableName) {
		this.targetTableName = targetTableName;
	}
	public Long getTargetTableSid() {
		return targetTableSid;
	}
	public void setTargetTableSid(Long targetTableSid) {
		this.targetTableSid = targetTableSid;
	}
	public File[] getAttachment() {
		return attachment;
	}
	public void setAttachment(File[] attachment) {
		this.attachment = attachment;
	}
	public String[] getAttachmentContentType() {
		return attachmentContentType;
	}
	public void setAttachmentContentType(String[] attachmentContentType) {
		this.attachmentContentType = attachmentContentType;
	}
	public String[] getAttachmentFileName() {
		return attachmentFileName;
	}
	public void setAttachmentFileName(String[] attachmentFileName) {
		this.attachmentFileName = attachmentFileName;
	}
	public Integer getTypes() {
		return types;
	}
	public void setTypes(Integer types) {
		this.types = types;
	}
	public Integer getIsTempFile() {
		return isTempFile;
	}
	public void setIsTempFile(Integer isTempFile) {
		this.isTempFile = isTempFile;
	}

	private FileService fileService;
	
	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}

	/**
	 * 上传附件
	 * @return
	 * lilang 
	 * 2013-6-24下午6:18:07
	 * @throws Exception 
	 */
	public String  upload() throws Exception{
		List<SmFile> smFiles = bulidFiles();
		if(smFiles.isEmpty()){
			this.renderJsonError("");
			return JSON;
		}
		this.fileService.saveAll(smFiles);
		this.rederTypeJsonSuccess(jsonUtils.getExtArrayJson(smFiles));
		//this.renderJsonSuccess(jsonUtils.getExtArrayJson(smFiles));
		return JSON;
	}
	
	/**
	 * 上传附件
	 * @return
	 * lilang 
	 * 2013-6-24下午6:18:07
	 * @throws Exception 
	 */
	public String  uploadImg() throws Exception{
		List<SmFile> smFiles = bulidImgFiles();
		if(smFiles.isEmpty()){
			this.renderJsonError("");
			return JSON;
		}
		this.fileService.saveAll(smFiles);
		if(smFiles.size()>0){
			this.rederImgJsonSuccess("success", smFiles.get(0).getUrl());
		}else{
			this.rederImgJsonSuccess("success", "");
		}
		
		//this.renderJsonSuccess(jsonUtils.getExtArrayJson(smFiles));
		return JSON;
	}
	
	/**
	 * 下载附件
	 * @return
	 * lilang 
	 * 2013-6-24下午6:18:39
	 */
	public String download(){
		SmFile smFile = null;
		if(null!=entity.getSid()){
			smFile = this.fileService.findByParmkeys(entity.getSid());
		}else if(null!=entity.getTargetTableSid()){
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("targetTableSid", entity.getTargetTableSid());
			params.put("targetTableName", entity.getTargetTableName());
			List<SmFile> smFiles=this.fileService.findParByList(params);
			if(smFiles.size()>0){
				smFile = smFiles.get(0);
			}
		}
		if(smFile==null){
			//下载失败 没有想过数据
			return "downError"; 
		}
		OutputStream outputstream = null;
		BufferedInputStream input = null;
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			String agent = request.getHeader("USER-AGENT");
			String outFileName = smFile.getCname();
	        if ((agent != null) && (-1 != agent.indexOf("MSIE")))
	        	outFileName = URLEncoder.encode(outFileName, "UTF-8");
	        else if ((agent != null) && (-1 != agent.indexOf("Mozilla"))) {
	        	outFileName = MimeUtility.encodeText(outFileName, "UTF8", "B");
	        }
	        response.setContentType(smFile.getFileType());
	        File file=new File(smFile.getUrl());
	        response.setContentLength(Integer.valueOf(String.valueOf(file.length())));
	        response.setHeader("Content-disposition", "attachment;filename=\""+ outFileName + "\"");
	        outputstream = response.getOutputStream();
			input = new BufferedInputStream(new java.io.FileInputStream(file));
			byte[] buffer = new byte[4096];
			int len = 0;
			while ((len = input.read(buffer)) > 0) {
				outputstream.write(buffer,0,len);
				outputstream.flush();
			}
			}catch (Exception e) {
			logger.error(e.getStackTrace());
		}finally{
			//关闭输入流
			if(null!=input){
				try {
					input.close();
				} catch (IOException e) {
					logger.error(e.getStackTrace());
				}
			}
			//关闭输出流
			if(null!=outputstream){
				try {
					outputstream.flush();
					outputstream.close();
				} catch (IOException e) {
					logger.error(e.getStackTrace());
				}
			}
		}
		return JSON;
	}
	
	private List<SmFile> bulidImgFiles(){
		List<SmFile> smFiles = new ArrayList<SmFile>();
		if(null==this.imgFile){
			return smFiles;
		}
		for(File file:imgFile){
			String newFileUrl = FileUtils.getNewPath(localUrl);
			File dirs = new File(FileUtils.getLocalUrl());
			File newFile = new File(newFileUrl);
			if(!dirs.exists()){
				dirs.mkdirs();
			}
			FileUtils.copyFile(file, newFile);
			SmFile sf = new SmFile();
			sf.setCname(localUrl);
			sf.setUrl(newFileUrl);
			sf.setCreatedt(new Date());
			sf.setLengths(file.length());
			sf.setFileType("text/jpg");
			sf.setTargetTableName("UP_IMG");
			sf.setTargetTableSid(targetTableSid);
			//如果是空表示临时的
			sf.setIsFormal(targetTableSid==null?0:1);
			sf.setTypes(0);
			smFiles.add(sf);
			try{
				//添加转换
				pushConvert(newFileUrl);
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return smFiles;
	}
	
	
	private List<SmFile> bulidFiles(){
		List<SmFile> smFiles = new ArrayList<SmFile>();
		if(null==this.attachment){
			return smFiles;
		}
		int index=0;
		for(File file:attachment){
			String newFileUrl = FileUtils.getNewPath(this.attachmentFileName[index]);
			File dirs = new File(FileUtils.getLocalUrl());
			File newFile = new File(newFileUrl);
			if(!dirs.exists()){
				dirs.mkdirs();
			}
			FileUtils.copyFile(file, newFile);
			SmFile sf = new SmFile();
			sf.setCname(this.attachmentFileName[index]);
			sf.setUrl(newFileUrl);
			sf.setCreatedt(new Date());
			sf.setLengths(file.length());
			sf.setFileType(this.attachmentContentType[index]);
			sf.setTargetTableName(targetTableName);
			sf.setTargetTableSid(targetTableSid);
			//如果是空表示临时的
			sf.setIsFormal(targetTableSid==null?0:1);
			sf.setTypes(0);
			index++;
			smFiles.add(sf);
			try{
				//添加转换
				//pushConvert(newFileUrl);
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return smFiles;
	}
	/**
	 *  添加转换
	 * @param url
	 * lilang 
	 * 2013-6-27上午10:20:24
	 */
	private void pushConvert(String url){
		String tempfile = url.toLowerCase();
		String fix = tempfile.substring(tempfile.lastIndexOf(ToolUtils.PIONT));
		// 转换office文档
		if (Convert2swf.SWF2TYPE.indexOf(fix)>=0) {
			ConvertThread.push(url);
			if(!ConvertThread.IS_RUN){
				ConvertThread.getInstance().start();
			}
		}
	}
	/**
	 * 删除附件
	 * @return
	 * lilang 
	 * 2013-6-27下午1:20:20
	 */
	public String delete(){
		if(entity.getSid()!=null){
			SmFile smfile = this.fileService.findByParmkeys(entity.getSid());
			FileUtils.deleteFile(new File(smfile.getUrl()));
			this.fileService.delete(smfile);
		}
		this.renderJsonSuccess();
		return JSON;
	}
	

}
